package app.purchase.a571xz.com.myandroidframe.httpservice.retrofit;


import com.facebook.stetho.okhttp3.StethoInterceptor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import app.purchase.a571xz.com.myandroidframe.config.AppConfig;
import app.purchase.a571xz.com.myandroidframe.httpservice.retrofit.converter.CustomGsonConverterFactory;
import app.purchase.a571xz.com.myandroidframe.httpservice.retrofit.cookie.CookieJarImp;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * retrofit 网络请求服务
 */
public class RetrofitService {

    private static RetrofitService retrofitService;
    //retrofit对象
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    public RetrofitService() {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();

        //正式环境下log关闭
        if (AppConfig.IS_HTTP_LOG) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(httpLoggingInterceptor);
            builder.addNetworkInterceptor(new StethoInterceptor());
        }
//        if (AppConfig.IS_SERVICE_CACHE) {
//            //自定义缓存
//            //CacheInterceptor cacheInterceptor = new CacheInterceptor();
//            //builder.addNetworkInterceptor(cacheInterceptor);
//            //缓存10M
//            File cacheDir = new File(BaseApplication.getInstance().getCacheDir(), "response");
//            //缓存的最大尺寸10m
//            Cache cache = new Cache(cacheDir, 1024 * 1024 * 10);
//            builder.cache(cache);
//        }


        builder.connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .cookieJar(new CookieJarImp());
        okHttpClient = builder.build();
        retrofit = new Retrofit.Builder().
                baseUrl(AppConfig.BASE_URL).
                //自定义的Gson转换器
                addConverterFactory(CustomGsonConverterFactory.create()).
                addCallAdapterFactory(RxJava2CallAdapterFactory.create()).
                client(okHttpClient).
                build();

    }

    public static RetrofitService getInstance(){
        if (retrofitService == null) {
            synchronized (RetrofitService.class) {
                if (retrofitService == null)
                    retrofitService = new RetrofitService();
            }
        }
        return retrofitService;
    }


    public static <T> T getBaseApi(Class<T> clazz) {
        getInstance();
        return retrofitService.retrofit.create(clazz);
    }

    //Get网络请求
    public static ApiService getApi() {
        return getBaseApi(ApiService.class);
    }

}
